<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use DB;
use App\Repositorys\AccountRepository;
use App\Repositorys\SmsRepository;
use App\Repositorys\OssRepository;
use Jenssegers\Agent\Agent;
use Illuminate\Support\Facades\Cookie;

class AccountController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->middleware('CheckUserLogin')->except(['getLoginUser', 'wx_login1', 'wx_login2']);
    }

    public function getLoginUser()
    {
        $user = getLoginUser();
        return jsonSuccess($user);
    }

    public function wx_login1(Request $request)
    {
		$appid = Config('common.wxapp.appid');
		$secret = Config('common.wxapp.secret');
        $code = $request->code;
		$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $res = curl_get($url);
		$res = json_decode($res, true);
		$unionid = isset($res['unionid']) ? $res['unionid'] : '';
		$openid = $res['openid'];
		$sessionKey = $res['session_key'];
		$code2seesion = base64_encode($unionid .'[luck]'. $openid .'[luck]'. $sessionKey);

        $return_data = ['code2seesion' => '', 'user_token' => ''];
		$user = DB::table('user')->where('wx_openid', $openid)->first();
		if (!empty($user)) {
			if ($user->status == 0) return jsonFailed('该账户已关闭');
			$return_data['user_token'] = app(AccountRepository::class)->loginSuccess($user->id);
		} else {
			$return_data['code2seesion'] = $code2seesion;
		}
		return jsonSuccess($return_data);
    }

    public function wx_login2(Request $request)
    {
        DB::beginTransaction();
        try {
            $appid = Config('common.wxapp.appid');
            $code2seesion = base64_decode($request->code2seesion);
            $array = explode('[luck]', $code2seesion);
            $unionid = $array['0'];
            $openid = $array['1'];
            $sessionKey = $array['2'];
            $iv = $request->iv;
            $encryptedData = $request->encryptedData;
            $user_info = json_decode($request->user_info, true);

            $WXBizDataCrypt = new \App\Extensions\wxApp\WXBizDataCrypt($appid, $sessionKey);
            $errCode = $WXBizDataCrypt->decryptData($encryptedData, $iv, $data);
            if ($errCode) return jsonFailed('登录失败');
            $data = json_decode($data, true);

            $user = DB::table('user')->where('phone', $data['phoneNumber'])->first();
            if (!empty($user)) {
                DB::table('user')->where('id', $user->id)->update(['wx_openid' => $openid, 'wx_unionid' => $unionid]);
                $user_id = $user->id;
            } else {
                $user_data = [];
                $user_data['wx_unionid'] = $unionid;
                $user_data['wx_openid'] = $openid;
                $user_data['phone'] = $data['phoneNumber'];
                $user_data['nickname'] = $user_info['nickName'];
                if (isset($user_info['gender'])) {
                    if ($user_info['gender'] == 1) $user_data['sex'] = '男';
                    if ($user_info['gender'] == 2) $user_data['sex'] = '女';
                }
                if (isset($user_info['avatarUrl']) && !empty($user_info['avatarUrl'])) {
                    $user_data['avatar'] = '/' . download_image($user_info['avatarUrl'], 'swb/upload/' . date('Ymd') . '/');
                }
                $user_id = DB::table('user')->insertGetId($user_data);
                if (isset($user_data['avatar']) && !empty($user_data['avatar'])) {
                    app(OssRepository::class)->uploadFile($user_data['avatar']);
                    DB::table('image')->insert(['path' => $user_data['avatar'], 'user_id' => $user_id, 'type' => 'user_avatar']);
                }
            }

            $return_data['user_token'] = app(AccountRepository::class)->loginSuccess($user_id);
            DB::commit();
            return jsonSuccess($return_data);
        } catch (\Throwable $th) {
            DB::rollBack();
            return jsonFailed($th->getMessage());
            return jsonFailed('登录失败，请联系管理员，谢谢~');
        }
    }
}
